import { Component } from '@angular/core';
import {NavController, ModalController, ActionSheetController} from 'ionic-angular';
import { Camera, File } from 'ionic-native';
import {Storage} from "@ionic/storage";

/*
  Generated class for the Photo page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-photo',
  templateUrl: 'photo.html'
})
export class PhotoPage {
  private _imgUrls: Array<string>;

  constructor(public navCtrl: NavController,
              public modalCtrl: ModalController,
              public storage: Storage,
              public actionSheetCtrl: ActionSheetController
  ) {
    // TODO get picture data from server

    storage.get('photo_list').then((photo_list: Array<string>) => {
      if (photo_list == null)
      {
        storage.set('photo_list', []);
        photo_list = [];
      }
      this.photo_list = photo_list.slice();
      this._imgUrls = photo_list.map(e => {
        return File.cacheDirectory+e;
      });
    });

    // TODO sync & download photo_list with server
  }

  private photo_list: Array<string> = [];


  get imgUrls(): Array<string> {
    return this._imgUrls;
  }
  set imgUrls(v) {
    this._imgUrls = v;
    this.storage.set('photo_list', this.imgUrls);
  }

  presentPhotoSelect()
  {
    let photo_select_success_cb = (imageData: string) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64:
      // TODO upload img then get img url from server
      let new_file_name = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        let r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
      });
      let file_name = imageData.split('/').pop();

      File.moveFile(File.tempDirectory, file_name, File.cacheDirectory, new_file_name).then(() => {
        this.imgUrls.push(File.cacheDirectory+new_file_name);
        this.photo_list.push(new_file_name);
        this.storage.set('photo_list', this.photo_list);
      });

    };

    let photo_select_err_cb = (err) => {
      // Handle error
    };

    let actionSheet = this.actionSheetCtrl.create({
      title: 'Upload Photo',
      buttons: [
        {
          text: 'From Gallery',
          handler: () => {
            Camera.getPicture({
              quality: 100,
              allowEdit: true,
              sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
              mediaType: Camera.MediaType.PICTURE,
              saveToPhotoAlbum: false,
              destinationType: Camera.DestinationType.FILE_URI
            }).then(photo_select_success_cb, photo_select_err_cb);

          }
        },
        {
          text: 'From Camera',
          handler: () => {
            Camera.getPicture({
              quality: 100,
              allowEdit: true,
              sourceType: Camera.PictureSourceType.CAMERA,
              mediaType: Camera.MediaType.PICTURE,
              saveToPhotoAlbum: true,
              destinationType: Camera.DestinationType.FILE_URI
            }).then(photo_select_success_cb, photo_select_err_cb);

          }
        },
        {
          text: 'Cancel',
          role: 'cancel'
        }
      ]
    });

    actionSheet.present();
  }
}
